
using System;
using System.Collections.Generic;
using foundation.events;
namespace foundation
{

    [AttributeUsage(AttributeTargets.Method)]
    public sealed class EvtAttribute : Attribute
    {
        public string type;
        public string[] events;
        public EvtAttribute(string type, params string[] events)
        {
            this.type = type;
            this.events = events;
        }

        public static Dictionary<string, MiniDispatcher> dict = new Dictionary<string, MiniDispatcher>();

        public static void registerEvent(object obj, int priority = 0)
        {
            var t = obj.GetType();
            var methods = t.GetMethods();
            var EvtAttributeType = typeof(EvtAttribute);
            foreach (var method in methods)
            {
                foreach (EvtAttribute attribute in method.GetCustomAttributes(EvtAttributeType, true))
                {
                    var type = attribute.type;
                    if (dict.ContainsKey(type))
                    {
                        var instance = dict[type];
                        foreach (var evt in attribute.events)
                        {
                            instance.AddEventListener(evt, method, obj, priority);
                        }
                    }
                }
            }
        }


        public static void removeEvent(object obj)
        {
            var t = obj.GetType();
            var methods = t.GetMethods();
            var EvtAttributeType = typeof(EvtAttribute);
            foreach (var method in methods)
            {
                foreach (EvtAttribute attribute in method.GetCustomAttributes(EvtAttributeType, true))
                {
                    var type = attribute.type;
                    if (dict.ContainsKey(type))
                    {
                        var instance = dict[type];
                        foreach (var evt in attribute.events)
                        {
                            instance.RemoveEventListener(evt, method, obj);
                        }
                    }
                }
            }
        }
    }

    public class InterestEventDispatcher : MiniDispatcher
    {
        public InterestEventDispatcher(string type)
        {
            var dict = EvtAttribute.dict;
            if (false == dict.ContainsKey(type))
            {
                dict[type] = this;
            }
        }
    }


    public class EVENT_CONST
    {
        public const string EVT = "evt";

        public const string SOCKET = "socket";
    }



    public class Facade
    {
        public static InterestEventDispatcher EVT;
        public static InterestEventDispatcher SOCKET;

        public static void init()
        {
            EVT = new InterestEventDispatcher(EVENT_CONST.EVT);
            SOCKET = new InterestEventDispatcher(EVENT_CONST.SOCKET);
        }
    }

}